<template>
  <PageWrapper contentFullHeight fixedHeight contentClass="main-box">
    <a-card class="common-card subitem-box" title="分项">
      <a-space wrap>
        <template v-for="_i in commonConfig.subitem" :key="_i.itemCode">
          <a-button @click="clickedBtn(_i)" :class="_i.active ? 'subitem-btn-focus' : 'subitem-btn'">{{ _i.itemName
          }}</a-button>
        </template>
      </a-space>
    </a-card>
    <div class="content-box">
      <a-card class="common-card" :title="`${commonConfig.currentBtn}的数据`">
        <template #extra>
          <a-space>
            <DatePicker v-model:value="dateMonthValue" picker="month"> </DatePicker>
            <a-button type="primary" @click="handleExport">导出</a-button>
          </a-space>
        </template>
        <BasicTable @register="registerTable"></BasicTable>
      </a-card>
    </div>
    <!-- <div class="content-box">
      <a-card class="common-card flex table-box">
        <TotalTable ref="totalTableRef" :loading="loadingTotalTableRef"></TotalTable>
      </a-card>
    </div> -->
  </PageWrapper>
</template>
<script setup>
import { ref, onMounted, reactive, watch } from 'vue'
import { DatePicker } from 'ant-design-vue'
import { PageWrapper } from '@/components/Page'
import Icon from '@/components/Icon/Icon.vue'
import { BasicTable, useTable } from '@/components/Table'
import { cloneDeep } from 'lodash-es'
import TotalTable from './totalTable.vue'
import { getByParentByDict, getEleTypeOneReport, getEleTypeOneReportBuilding } from '@/api/power/electricity/electricity.ts'
import { getDictListByCode } from '@/api/sys/dict'
import dayjs, { Dayjs } from 'dayjs'
import { GeneralExportData } from '@/api/common/chart.ts'
import {
  downloadByData,
} from '@/utils/file/download';
import { message } from 'ant-design-vue';

const dateMonthValue = ref(dayjs());

const searchInfos = reactive({
  queryType: 'month',
  startDay: dateMonthValue.value.format('YYYY-MM'),
  dictCode: "electrical_science_classification_of_each_department",
  itemName: "分类"
});

const commonConfig = reactive({
  subitem: [], //点击按钮的所有配置
  currentBtn: '', //当前按钮名称,
  dictCodeInfo: [],  //分项信息
  searchInfo: {
    queryType: 'month',
    classifyId: '', //电科_各科室分类,list第58行
  }
});

const dictCode = 'electrical_science_classification_of_each_department';

const handleExport = async () => {
  // 更新 searchInfos 中的 startDay 为最新的 dateMonthValue 格式化值
  searchInfos.startDay = dateMonthValue.value.format('YYYY-MM');
  console.log(searchInfos);

  try {
    const { data, headers } = await GeneralExportData(searchInfos);
    let contentDisposition = decodeURIComponent(headers["content-disposition"]);
    const filenameMatch = contentDisposition.match(/filename\*=UTF-8''(.+)|filename="(.+)"|filename=(.+)/);
    const fileName = filenameMatch[1] || filenameMatch[2] || filenameMatch[3];
    downloadByData(data, fileName);
    message.success("导出成功");
  } catch (error) {
    console.error('导出失败', error);
    message.error("导出失败");
  }
};

const clickedBtn = (info) => {
  console.log('点击按钮----', info);
  //更新按钮样式
  const config = cloneDeep(commonConfig.subitem);
  config.forEach((item) => {
    item.active = item.itemCode === info.itemCode;
  });
  commonConfig.subitem = [...config];
  //更新table的名称
  commonConfig.currentBtn = info.itemName;
  commonConfig.searchInfo.classifyId = info.itemCode;
  getData();
  getTotalData();
};

const loadingTotalTableRef = ref(false);
const totalTableRef = ref();
const chartData = ref();

const [registerTable, { setLoading, setColumns, setTableData }] = useTable({
  rowKey: 'id',
  columns: [],
  pagination: false,
  formConfig: {
    labelWidth: 120,
  },
  bordered: true,
  striped: true,
  // showSummary: true,
});

onMounted(async () => {
  getTypeList();
  getTotalData();
});

watch(
  () => dateMonthValue.value,
  (readyVal) => {
    searchInfos.startDay = readyVal.format('YYYY-MM');
    getData();
    getTotalData();
  },
);

const formatHeader = (headerData) => {
  const headerList = [
    {
      title: '低压出线柜编号',
      dataIndex: 'code',
      width: 120,
      fixed: 'left',
      merge: true,
    },
    {
      title: '描述',
      dataIndex: 'name',
      width: 120,
      fixed: 'left',
      merge: true,
    },
  ];

  headerData.forEach((item) => {
    console.log(item);

    headerList.push({
      title: `${dayjs(item).format('D')}`,
      dataIndex: `${dayjs(item).format('D')}` - 1,
      width: 100,
      customRender: ({ text }) => {
        if (typeof text === 'number') {
          return text;
        } else {
          return text || '--';
        }
      },
    });
  });
  console.log(headerList);

  setColumns(headerList);
};

const formatTableData = (tableData) => {
  const { xaxisList, yaxisList } = tableData;
  const data = tableData.map((item) => {
    const { data, ...others } = item;
    const record = { ...others };
    data.forEach((item, index) => {
      record[index] = item;
    });
    return record;
  });
  setTableData(data);
};

const getTypeList = async () => {
  const res = await getDictListByCode(dictCode);
  if (res && res.length > 0) {
    commonConfig.dictCodeInfo = res;
    commonConfig.subitem = res;
    getSubItem(res);
  }
};

//获取分项名称并按sort字段排序
const getSubItem = async (dictCodeInfo) => {
  if (dictCodeInfo && dictCodeInfo.length > 0) {
    // commonConfig.subitem = dictCodeInfo.map((item, index) => {
    //   let obj = {
    //     itemName: item.itemName,
    //     itemCode: item.itemCode,
    //   };
      // // 初始化加载时，如果url state中存在classifyId,则使用url中的值,否则使用默认值
      // if (history.state?.classifyName === item.itemName) {
      //   //初始化数据
      //   obj.active = true;
      //   commonConfig.currentBtn = history.state.itemName;
      //   commonConfig.searchInfo = {
      //     queryType: 'month',
      //     classifyId: history.state.itemCode,
      //   };
      //   getData();
      // } else if (!history.state?.classifyName && index === 0) {
      //   // 默认初始化第一条数据
      //   obj.active = true;
      //   commonConfig.currentBtn = obj.itemName;
      //   commonConfig.searchInfo = {
      //     queryType: 'month',
      //     classifyId: obj.itemCode,
      //   };
      //   getData();
    //   } else {
    //     obj.active = false;
    //   }
    //   return obj;
    // });
    let fns = []
    fns = dictCodeInfo.map(item => getByParentByDict({
      dictCode: item.dictCode,
      itemName: item.itemName,
    }))
      Promise.all(fns).then((res) => {
        console.log(res, 'res')
        let allResult = []
        if (res.length > 0) {
          allResult = res.flat()
          console.log(allResult, 'allResult')
          commonConfig.subitem = allResult.map((item, index) => {
            let obj = {
              itemName: item.classifyName,
              itemCode: item.classifyId,
            };
            console.log(11)
             // 初始化加载时，如果url state中存在classifyId,则使用url中的值,否则使用默认值
            if (history.state?.classifyName === item.classifyName) {
              //初始化数据
              obj.active = true;
              commonConfig.currentBtn = history.state.classifyName;
              commonConfig.searchInfo = {
                queryType: 'month',
                classifyId: history.state.classifyId,
              };
              getData();
            } else if (!history.state?.classifyName && index === 0) {
              // 默认初始化第一条数据
              obj.active = true;
              commonConfig.currentBtn = obj.itemName;
              commonConfig.searchInfo = {
                queryType: 'month',
                classifyId: obj.itemCode,
              };
              getData();
            } else {
              obj.active = false;
            }
            return obj;
          });
        }
      })
      .finally(() => {
        console.log('拿到分项名称');
      });
  }
};

const getData = () => {
  setLoading(true);
  getEleTypeOneReport({
    queryType: 'month',
    startDay: dateMonthValue.value.format('YYYY-MM'),
    classifyId: commonConfig.searchInfo.classifyId,
  })
    .then((e) => {
      formatHeader(e.xaxisList);
      formatTableData(e.yaxisList);
    })
    .catch((e) => {
      console.log('分项数据报错', e);
    })
    .finally(() => {
      setLoading(false);
    });
};

//总计
const getTotalData = () => {
  loadingTotalTableRef.value = true;
  getEleTypeOneReportBuilding({
    queryType: 'month',
    startDay: dateMonthValue.value.format('YYYY-MM'),
    // classifyId: '1810966241494437888', //电科_各科室分类,list第58行
    classifyId: commonConfig.searchInfo.classifyId,
  })
    .then((e) => {
      totalTableRef.value.setData(e.xaxisList, e.yaxisList);
    })
    .catch((e) => {
      totalTableRef.value.setData([], []);
    })
    .finally(() => {
      loadingTotalTableRef.value = false;
    });
};
</script>
<style scoped lang="scss">
.subitem-box {

  //分项按钮的样式-开始
  .subitem-btn {
    width: 112px;
    height: 28px;
    border: 1px solid rgb(208 212 223 / 100%);
    border-radius: 2px;
    background: #f3f7fb;
    box-shadow: none;
    color: #181818;
    font-size: 12px;
    font-weight: 400;
  }

  .subitem-btn-focus {
    width: 112px;
    height: 28px;
    border: 1px solid rgb(0 103 204 / 100%);
    border-radius: 2px;
    background: rgb(0 103 204 / 15%);
    box-shadow: none;
    color: #0067cc;
  }

  .ant-space {
    margin-bottom: 0 !important;
  }

  //分项按钮的样式-结束
}

.content-box {
  display: flex;
  flex: 1;
  flex-direction: column;
  margin-top: 8px;
  background: #fff;
  overflow: hidden;
  :deep(.ant-table-body) {
    height: 100% !important;
  }

  .table-box {
    flex: 1;
    flex-shrink: 0;
    overflow: hidden;
  }

  :deep(.ant-table-wrapper) {
    padding: 0;
  }
}
</style>